package com.zhouwr.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.jeecg.common.constant.CommonConstant;

import java.util.List;

/**
 * Tcp服务器同步接收器
 *
 * @author zhouwenrong
 */
@Slf4j
@ChannelHandler.Sharable
public class Wireless120SyncReceiver extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        log.info("同步接收器 >>>> {}", Hex.encodeHexString(ByteBufUtil.getBytes(msg)));
        AttributeKey<Object> attrKey = AttributeKey.valueOf(CommonConstant.SYNC_RECEIVE);
        log.info("channel.hasAttr(attrKey) >>>>> {}", ctx.channel().hasAttr(attrKey));
        if (ctx.channel().hasAttr(attrKey)) {
            Attribute<Object> attribute = ctx.channel().attr(attrKey);
            synchronized (attribute) {
                attribute.set(msg);
                attribute.notify();
            }
        }
        msg.retain();
        ctx.fireChannelRead(msg);
    }
}
